<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\api\logic;


use app\common\{enum\notice\NoticeEnum,
    enum\user\AccountLogEnum,
    enum\user\UserTerminalEnum,
    enum\YesNoEnum,
    logic\AccountLogLogic,
    logic\BaseLogic,
    model\user\User,
    model\user\UserAuth,
    model\user\UserGroup,
    model\user\UserCardLog,
    service\FileService,
    service\sms\SmsDriver,
    service\wechat\WeChatMnpService
};
use think\facade\Config;

/**
 * 会员逻辑层
 * Class UserLogic
 * @package app\shopapi\logic
 */
class UserLogic extends BaseLogic
{

    /**
     * @notes 个人中心
     * @param array $userInfo
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author 段誉
     * @date 2022/9/16 18:04
     */
    public static function center(array $userInfo): array
    {
        $user = User::where(['id' => $userInfo['user_id']])
            ->field('id,group_id,role_id,account,nickname,real_name,avatar,mobile,email')
            ->findOrEmpty();

        if (in_array($userInfo['terminal'], [UserTerminalEnum::WECHAT_MMP, UserTerminalEnum::WECHAT_OA])) {
            $auth = UserAuth::where(['user_id' => $userInfo['user_id'], 'terminal' => $userInfo['terminal']])->find();
            $user['is_auth'] = $auth ? YesNoEnum::YES : YesNoEnum::NO;
        }
        $user['user_money'] = UserGroup::where('id', $user['group_id'])
            ->value('user_money');
        return $user->toArray();
    }


    /**
     * @notes 个人信息
     * @param $userId
     * @return array
     * @author 段誉
     * @date 2022/9/20 19:45
     */
    public static function info(int $userId)
    {
        $user = User::where(['id' => $userId])
            ->field('id,group_id,sn,sex,account,password,nickname,real_name,avatar,mobile,create_time,user_money')
            ->findOrEmpty();
        $user['has_password'] = !empty($user['password']);
        $user['has_auth'] = self::hasWechatAuth($userId);
        $user['version'] = config('project.version');
        $user->hidden(['password']);
        return $user->toArray();
    }

    //获取团队成员
    public static function groupUser(int $groupId)
    {
        $user = User::where(['group_id' => $groupId])
            ->field('id,pid,role_id,account,email,is_disable,mobile,create_time')
            ->select();
        return $user->toArray();
    }


    public static function groupInfo(int $groupId)
    {
        $userGroup = UserGroup::where('id', $groupId)
            ->field(['id', 'company_name', 'email', 'mobile', 'pid', 'user_money', 'from_business', 'card_used', '(card_sum - card_used) as card_free', 'card_sum', 'card_price', 'card_limit', 'abbreviation', 'serverchargerate', 'serverUchargerate'])
            ->find();
        return $userGroup->toArray();
    }

    //获取平台组长
    public static function groupLeader(int $groupId)
    {
        $userGroup = User::where('group_id', $groupId)
            ->where('role_id', 3)
            ->field(['id', 'account', 'nickname'])
            ->select();
        return $userGroup->toArray();
    }

    public static function groupUserEdit(array $params)
    {
        try {
            $userId = $params['id'];
            $user = User::where(['id' => $userId])->findOrEmpty();
            if ($user->isEmpty()) {
                throw new \Exception('用户信息不存在');
            }
            if ($params['nickname']) {
                $user->nickname = $params['nickname'];
            }
            if ($params['role_id']) {
                $user->role_id = $params['role_id'];
            }

            if ($params['role_id'] > 3) {
                $user->pid = $params['pid'];
            }
            $passwordSalt = Config::get('project.unique_identification');
            // 重置密码
            if (isset($params['password']) && $params['password']) {
                $user->password = create_password($params['password'], $passwordSalt);
            }
            // 重置交易密码
            if (isset($params['secure_password']) && $params['secure_password']) {
                $user->secure_password = create_password($params['secure_password'], $passwordSalt);
            }

            //修改团员状态
            if (isset($params['is_disable']) && in_array($params['is_disable'], [1, 0])) {
                $user->is_disable = $params['is_disable'];
            }

            $user->save();
            return true;
        } catch (\Exception $e) {
            self::$error = $e->getMessage();
            return false;
        }
    }


    public static function buyCard(array $userInfo, array $params)
    {
        try {
            $groupId = $userInfo['group_id'];
            $userId = $userInfo['user_id'];
            $userGroup = UserGroup::where('id', $groupId)
                ->findOrEmpty();

            if ($userGroup->isEmpty()) {
                throw new \Exception('客户信息不存在');
            }

            $price = $params['num'] * $userGroup['card_price'];

            if ($userGroup['user_money'] < $price) {
                throw new \Exception('余额不足');
            }
            $userGroup->user_money -= $price;
            $userGroup->card_sum += $params['num'];

            if ($userGroup->card_sum > $userGroup->card_limit) {
                throw new \Exception('超过卡位购买限制');
            }

            $userGroup->save();

            AccountLogLogic::add(
                $groupId,
                AccountLogEnum::UM_DEC_ADMIN,
                AccountLogEnum::DEC,
                $price,
                '',
                '购买卡位数量' . $params['num'],
            );
            $data = [
                'user_id' => $userId,
                'group_id' => $groupId,
                'amount' => $price,
                'num' => $params['num'],
                'remark' => '',
            ];
            UserCardLog::create($data);
            return true;
        } catch (\Exception $e) {
            self::$error = $e->getMessage();
            return false;
        }

    }

    /**
     * @param int $groupId
     * @param array $params
     * @return void
     */
    public static function buyCardLog(array $userInfo)
    {
        $userCardLog = UserCardLog::where('l.group_id', $userInfo['group_id'])
            ->alias('l')
            ->join('sc_user u', 'l.user_id = u.id')
            ->field('l.*, u.account')
            ->select();
        return $userCardLog->toArray();
    }


    /**
     * @notes 设置用户信息
     * @param int $userId
     * @param array $params
     * @return User|false
     * @author 段誉
     * @date 2022/9/21 16:53
     */
    public static function setInfo(int $userId, array $params)
    {
        try {
            if ($params['field'] == "avatar") {
                $params['value'] = FileService::setFileUrl($params['value']);
            }

            return User::update([
                    'id' => $userId,
                    $params['field'] => $params['value']]
            );
        } catch (\Exception $e) {
            self::$error = $e->getMessage();
            return false;
        }
    }


    /**
     * @notes 是否有微信授权信息
     * @param $userId
     * @return bool
     * @author 段誉
     * @date 2022/9/20 19:36
     */
    public static function hasWechatAuth(int $userId)
    {
        //是否有微信授权登录
        $terminal = [UserTerminalEnum::WECHAT_MMP, UserTerminalEnum::WECHAT_OA, UserTerminalEnum::PC];
        $auth = UserAuth::where(['user_id' => $userId])
            ->whereIn('terminal', $terminal)
            ->findOrEmpty();
        return !$auth->isEmpty();
    }


    /**
     * @notes 重置登录密码
     * @param $params
     * @return bool
     * @author 段誉
     * @date 2022/9/16 18:06
     */
    public static function resetPassword(array $params)
    {
        try {
            // 校验验证码
            $smsDriver = new SmsDriver();
            if (!$smsDriver->verify($params['mobile'], $params['code'], NoticeEnum::FIND_LOGIN_PASSWORD_CAPTCHA)) {
                throw new \Exception('验证码错误');
            }

            // 重置密码
            $passwordSalt = Config::get('project.unique_identification');

            $password = create_password($params['password'], $passwordSalt);

            // 更新
            User::where('mobile', $params['mobile'])->update([
                'password' => $password
            ]);

            return true;
        } catch (\Exception $e) {
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * @notes 修改密码
     * @param $params
     * @param $userId
     * @return bool
     * @author 段誉
     * @date 2022/9/20 19:13
     */
    public static function changePassword(array $params, int $userId)
    {
        try {
            $user = User::findOrEmpty($userId);
            if ($user->isEmpty()) {
                throw new \Exception('用户不存在');
            }

            // 密码盐
            $passwordSalt = Config::get('project.unique_identification');

            if (!empty($user['password'])) {
                if (empty($params['old_password'])) {
                    throw new \Exception('请填写旧密码');
                }
                $oldPassword = create_password($params['old_password'], $passwordSalt);
                if ($oldPassword != $user['password']) {
                    throw new \Exception('原密码不正确');
                }
            }

            // 保存密码
            $password = create_password($params['password'], $passwordSalt);
            $user->password = $password;
            $user->save();

            return true;
        } catch (\Exception $e) {
            self::setError($e->getMessage());
            return false;
        }
    }

    public static function changeSecurePassword(array $params, int $userId)
    {
        try {
            $user = User::findOrEmpty($userId);
            if ($user->isEmpty()) {
                throw new \Exception('用户不存在');
            }

            // 密码盐
            $passwordSalt = Config::get('project.unique_identification');

            // 保存密码
            $password = create_password($params['password'], $passwordSalt);
            $user->secure_password = $password;
            $user->save();

            return true;
        } catch (\Exception $e) {
            self::setError($e->getMessage());
            return false;
        }
    }

    /**
     * @notes 获取小程序手机号
     * @param array $params
     * @return bool
     * @throws \Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface
     * @author 段誉
     * @date 2023/2/27 11:49
     */
    public static function getMobileByMnp(array $params)
    {
        try {
            $response = (new WeChatMnpService())->getUserPhoneNumber($params['code']);
            $phoneNumber = $response['phone_info']['purePhoneNumber'] ?? '';
            if (empty($phoneNumber)) {
                throw new \Exception('获取手机号码失败');
            }

            $user = User::where([
                ['mobile', '=', $phoneNumber],
                ['id', '<>', $params['user_id']]
            ])->findOrEmpty();

            if (!$user->isEmpty()) {
                throw new \Exception('手机号已被其他账号绑定');
            }

            // 绑定手机号
            User::update([
                'id' => $params['user_id'],
                'mobile' => $phoneNumber
            ]);

            return true;
        } catch (\Exception $e) {
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * @notes 绑定手机号
     * @param $params
     * @return bool
     * @author 段誉
     * @date 2022/9/21 17:28
     */
    public static function bindMobile(array $params)
    {
        try {
            // 变更手机号场景
            $sceneId = NoticeEnum::CHANGE_MOBILE_CAPTCHA;
            $where = [
                ['id', '=', $params['user_id']],
                ['mobile', '=', $params['mobile']]
            ];

            // 绑定手机号场景
            if ($params['type'] == 'bind') {
                $sceneId = NoticeEnum::BIND_MOBILE_CAPTCHA;
                $where = [
                    ['mobile', '=', $params['mobile']]
                ];
            }

            // 校验短信
            $checkSmsCode = (new SmsDriver())->verify($params['mobile'], $params['code'], $sceneId);
            if (!$checkSmsCode) {
                throw new \Exception('验证码错误');
            }

            $user = User::where($where)->findOrEmpty();
            if (!$user->isEmpty()) {
                throw new \Exception('该手机号已被使用');
            }

            User::update([
                'id' => $params['user_id'],
                'mobile' => $params['mobile'],
            ]);

            return true;
        } catch (\Exception $e) {
            self::setError($e->getMessage());
            return false;
        }
    }

    /**
     * @notes 更新用户邮箱
     * @param string $email 邮箱地址
     * @param int $userId 用户ID
     * @return bool
     * @author AI
     * @date 2023/12/12
     */
    public static function updateEmail(string $email, int $userId)
    {
        try {
            // 检查邮箱是否已被其他用户使用
            $exists = User::where('email', $email)
                ->where('id', '<>', $userId)
                ->find();

            if ($exists) {
                throw new \Exception('该邮箱已被其他用户使用');
            }

            // 更新用户邮箱
            $result = User::where('id', $userId)
                ->update(['email' => $email]);

            if (!$result) {
                throw new \Exception('更新邮箱失败');
            }

            return true;
        } catch (\Exception $e) {
            self::setError($e->getMessage());
            return false;
        }
    }

}